package com.rockcent.wechat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.lib.domain.Customer;
import com.rockcent.mall.lib.dto.CustomerDto;
import com.rockcent.mall.lib.repository.CustomerRepository;
import com.rockcent.wechat.helper.CustomerHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Created by oyhk on 15/11/29.
 * 是否登录过滤器
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    private CustomerHelper customerHelper;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        CustomerDto customerDto = customerHelper.getSession(request);
        log.info("customerDto:{}", customerDto);
        if (customerDto != null && customerDto.getId() != null) {
            return true;
        }

        String userToken = request.getHeader("userToken");

        if (StringUtils.isBlank(userToken)) {
            userToken = RequestUtils.getStringParameter(request, "userToken");
        }

        if (StringUtils.isBlank(userToken)) {
            String jr = objectMapper.writeValueAsString(new JsonResult<>("10001", "userToken 不能为空"));
            log.warn("======================>jsonResult : {}", jr);
            response.getWriter().print(jr);
            response.getWriter().close();
            return false;
        }
        String customerId = stringRedisTemplate.boundValueOps(Customer.REDIS_CUSTOMER_USER_TOKEN_PREFIX + userToken).get();
        if (StringUtils.isBlank(customerId)) {
            String jr = objectMapper.writeValueAsString(new JsonResult<>("10002", "userToken 无效"));
            log.warn("======================>jsonResult : {}", jr);
            response.getWriter().print(jr);
            response.getWriter().close();
            return false;
        }
        log.info("======================>customerId : {},userToken:{}", customerId, userToken);

        Customer customer = customerRepository.findOne(Long.valueOf(customerId));
        if (customer == null) {
            response.getWriter().print(objectMapper.writeValueAsString(new JsonResult<>("10002", "userToken 无效")));
            response.getWriter().close();
            return false;
        }

        log.info("======================>customer.mallId : {} , customerDto.mallId : {}", customer.getMallId(), customerDto.getMallId());
        if (!Objects.equals(customer.getMallId(), customerDto.getMallId())) {
            String jr = objectMapper.writeValueAsString(new JsonResult<>("10003", "客户不属于平台"));
            log.warn("======================>jsonResult : {}", jr);
            response.getWriter().print(jr);
            response.getWriter().close();
            return false;
        }

        // 设置 session
        customerHelper.setSession(customer, request, response);


        return super.preHandle(request, response, handler);
    }
}
